<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class School extends Backend
{

    /**
     * School模型对象
     * @var \app\admin\model\School
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\School;

    }
    public  function  import()
    {
        return parent::import();
    }
    public function searchlist()
    {
        $data = $this->model->field('id, schoolname')->select();
        $reust=[];
        foreach ($data as $key => $value) {
            $data[$key]['name']=$value['schoolname'];
            // $data[$key]['schoolname'] = $value['schoolname'];
        };

 // 调试输出 $data 的类型
//  dump($data);
    // 将查询结果转换为数组
    // $result = $data->toArray();

    // 返回 JSON 格式的数据
    return json($data);
    }

    /**
     * 删除学校的同时也删掉对应的所有学生。
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {


            foreach ($list as $item) {
                $count += $item->delete();
            }
             Db::name('user')->where('school_id','in',$ids)->delete();
 


            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
